﻿@page "/ip2region"

@if (isLoading)
{
    <Loading />
}
else
{
    <div class="plus-container ip-box">
        <div class="ip-search">
            <input type="text" placeholder="请输入IP地址" @bind="@ip" @bind:event="oninput" />
            <button @onclick="Search">查询</button>
        </div>
        @if (regions != null)
        {
            <div class="ip-region">
                @if (regions.Success)
                {
                    <p>当前IP：@regions.Result.First()</p>
                    <p>归属地：@string.Join(" ", regions.Result.Skip(1))</p>
                }
                else
                {
                    <p>@regions.Message</p>
                }
            </div>
        }
    </div>
}

@code {
    /// <summary>
    /// 加载中
    /// </summary>
    private bool isLoading = true;

    /// <summary>
    /// ip
    /// </summary>
    private string ip;

    /// <summary>
    /// regions
    /// </summary>
    private ServiceResult<List<string>> regions;

    /// <summary>
    /// 初始化
    /// </summary>
    /// <returns></returns>
    protected async override Task OnInitializedAsync()
    {
        await Common.SetTitleAsync("IP地址查询");

        await Ip2RegionAsync();
    }

    /// <summary>
    /// Ip2Region
    /// </summary>
    /// <returns></returns>
    private async Task Ip2RegionAsync()
    {
        isLoading = true;
        regions = await Http.GetFromJsonAsync<ServiceResult<List<string>>>($"/common/ip2region?ip={ip}");
        isLoading = false;
    }

    /// <summary>
    /// 查询按钮点击事件
    /// </summary>
    /// <returns></returns>
    private async Task Search()
    {
        if (string.IsNullOrEmpty(ip) || ip == regions.Result?.First())
        {
            return;
        }

        await Ip2RegionAsync();
    }
}